package cat.joronya.supermanager.team;

import java.text.NumberFormat;
import java.util.Locale;

import cat.joronya.supermanager.R;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.utils.ImageDownloader;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.*;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.View.*;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Activity to make changes using drag'n'drop based on images.
 */
@TargetApi(16)
public class MyTeamVisualChangesActivity extends Activity 
{
	public static final String TAG = "supermanager";
	
	private static final String URL_PHOTO_PLAYER = 
		"http://www.acb.com/fotos_cara/jugadores/J%sLACB58.jpg";
	
	protected int idequ;
	protected int day;
	
	protected Cursor favoritesCursor = null;
	protected String[] favoritesProjection = new String[]{
		Supermanager.Market.ID_PLAYER, 			// 0
		"m."+Supermanager.Market.CODI_PLAYER,	// 1
		Supermanager.Market.NAME,				// 2
		Supermanager.Market.NACIONALITY,		// 3
		Supermanager.Market.STATUS,				// 4
		Supermanager.Market.TEAM,				// 5
		Supermanager.Market.VS_TEAM,			// 6
		Supermanager.Market.AVERAGE,			// 7
		Supermanager.Market.PRICE,				// 8
		Supermanager.PlayerList.LIST_NAME,		// 9
		Supermanager.Market.POSITION			// 10
	};
	
	protected Cursor myTeamCursor = null;
	
	public Drawable defaultDrawable; 
	private final ImageDownloader imageDownloader = new ImageDownloader(this, Supermanager.PLAYERS, 105);
	
	private NumberFormat decform = null;
    private NumberFormat intform = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_team_visual_changes);
		
		// guardem id equip i jornada
        idequ = getIntent().getIntExtra("cat.joronya.supermanager.myteams.idequ",0);
        day = getIntent().getIntExtra("cat.joronya.supermanager.myteams.day",0);
        
        if( decform == null )
        {
        	decform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	decform.setMinimumFractionDigits(2);
        }
        if( intform == null )
        {
        	intform = NumberFormat.getNumberInstance(new Locale("es","ES"));
        	intform.setGroupingUsed(true);
        }
		
		LinearLayout players = (LinearLayout) findViewById(R.id.players);
		final float density = getResources().getDisplayMetrics().density;
		int width = (int)(density*115);
		int height = (int)(density*163);
		Log.d(TAG, "MyTeamVisualChangesActivity width: "+width+", height: "+height);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,height);
		
		String selectionFav = Supermanager.Market.DAY + " = ? AND "+Supermanager.PlayerList.LIST_NAME+" = ? ";
		String[] selectionArgsFav = new String[]{day+"", Supermanager.FAV_LISTNAME};
		String sortOrderFav = Supermanager.Market.POSITION+" DESC, "+Supermanager.Market.NAME+" ASC";
		
		favoritesCursor = getContentResolver().query(Supermanager.Market.CONTENT_URI, 
				favoritesProjection, selectionFav, selectionArgsFav, sortOrderFav);
		
		defaultDrawable = getResources().getDrawable(R.drawable.noplayer);
		
		while( favoritesCursor.moveToNext() )
		{
			// afegim jugador a la llista
			int i = favoritesCursor.getPosition();
			View playerView = inflateAndBindView();
			players.addView(playerView,i,params);
		}
		
		//TODO: recuperar el meu equip per inicialitzar equip
		String selectionTeam = Supermanager.MyTeamDetail.ID_EQU+" =? AND "+Supermanager.MyTeamDetail.DAY+" =? ";
		String[] selectionArgsTeam = new String[]{""+idequ,""+day};
		
		myTeamCursor = getContentResolver().query(Supermanager.MyTeamDetail.CONTENT_URI, 
				Supermanager.MyTeamDetail.PROJECTION, 
				selectionTeam, 
				selectionArgsTeam, 
				Supermanager.MyTeamDetail.NUM_POSITION_SORT_ORDER);
		
		while( myTeamCursor.moveToNext() )
		{
			// bindem dades dels meus jugadors a pista
			int i = myTeamCursor.getPosition();
			populateMyTeam();
		}
	}
	
	public void populateMyTeam()
	{
		int i = myTeamCursor.getPosition();
		String position = myTeamCursor.getString(18);
		int numPosition = myTeamCursor.getInt(19);
		String playerName = myTeamCursor.getString(26);
		String playerCode = myTeamCursor.getString(3);
		Log.d(TAG,"MyTeam player: "+playerName+", position: "+position+", numPosition: "+numPosition);
		
		View playerView;
		switch(numPosition)
		{
			case 1:
				playerView = findViewById(R.id.b1);
				break;
			case 2:
				playerView = findViewById(R.id.b2);
				break;
			case 3:
				playerView = findViewById(R.id.b3);
				break;
			case 4:
				playerView = findViewById(R.id.a4);
				break;
			case 5:
				playerView = findViewById(R.id.a5);
				break;
			case 6:
				playerView = findViewById(R.id.a6);
				break;
			case 7:
				playerView = findViewById(R.id.a7);
				break;
			case 8:
				playerView = findViewById(R.id.p8);
				break;
			case 9:
				playerView = findViewById(R.id.p9);
				break;
			case 10:
				playerView = findViewById(R.id.p10);
				break;
			case 11:
			default:
				playerView = findViewById(R.id.p11);
				break;
		}
		
		// afegim img en background...
		imageDownloader.download(String.format(URL_PHOTO_PLAYER, playerCode), (ImageView)playerView, defaultDrawable);
		
		/*playerView.setOnDragListener(new MyDragListener());*/
	}
	
	/**
	 * Infla i popula una view del list lateral.
	 * @return
	 */
	public View inflateAndBindView()
	{
		LayoutInflater inflater = getLayoutInflater();
		View playerView = inflater.inflate(R.layout.my_team_visual_list_row, null);
		
		String codPlayer = favoritesCursor.getString(1);
		String name = favoritesCursor.getString(2);
		String nacionality = favoritesCursor.getString(3);
		String status = favoritesCursor.getString(4);
		String team = favoritesCursor.getString(5);
		String vsteam = favoritesCursor.getString(6);
		float average = favoritesCursor.getFloat(7);
		int price = favoritesCursor.getInt(8);
		String position = favoritesCursor.getString(10);
		
		Log.d(TAG,"player "+name);
		
		// position
		TextView positionView = (TextView)playerView.findViewById(R.id.position);
		if( Supermanager.GUARD_POSITION.equals(position) )
		{
			positionView.setText(getResources().getString(R.string.market_row_position_guard));
		}
		else if( Supermanager.CENTER_POSITION.equals(position))
		{
			positionView.setText(getResources().getString(R.string.market_row_position_center));
		}
		else if( Supermanager.FORWARD_POSITION.equals(position))
		{
			positionView.setText(getResources().getString(R.string.market_row_position_forward));
		}
		
		// player name
		TextView playerNameView = (TextView)playerView.findViewById(R.id.playername);
		playerNameView.setText(name);
		
		// team
		TextView teamView = (TextView)playerView.findViewById(R.id.team);
		teamView.setText(team);
		
		// vs team
		TextView vsteamView = (TextView)playerView.findViewById(R.id.vsteam);
		vsteamView.setText(vsteam);
		
		// price
		TextView priceView = (TextView)playerView.findViewById(R.id.player_price);
		priceView.setText(intform.format(price)+"€");
		
		// average
		TextView averageView = (TextView)playerView.findViewById(R.id.player_average);
		averageView.setText(decform.format(average));
		
		// avatar
		ImageView avatarView = (ImageView)playerView.findViewById(R.id.avatar);
		avatarView.setTag(codPlayer);
		avatarView.setScaleType(ImageView.ScaleType.FIT_XY);
		
		// Sets a long click listener for the ImageView using an anonymous listener object that
		// implements the OnLongClickListener interface
		avatarView.setOnLongClickListener(new OnLongClickListener()
		{
			public boolean onLongClick(View view) 
			{
				/*/ClipData data = ClipData.newPlainText("Player", "");
				DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(view);
				view.startDrag(data, shadowBuilder, view, 0);
				//view.setVisibility(View.INVISIBLE);*/
				return true;
			}
		});
		
		// afegim img en background...
		imageDownloader.download(String.format(URL_PHOTO_PLAYER, codPlayer), avatarView, defaultDrawable);
		
		// status
		View stickView = playerView.findViewById(R.id.stick);
		if( "lesio.png".equals(status) )
		{
			stickView.setVisibility(View.VISIBLE);
			ImageView statusView = (ImageView)stickView;
			statusView.setImageResource(R.drawable.lesio);
			statusView.bringToFront();
		}
		else if( "semafor.png".equals(status) )
		{
			stickView.setVisibility(View.VISIBLE);
			ImageView statusView = (ImageView)stickView;
			// TODO: guardar drawable de semafor
			statusView.setImageResource(R.drawable.lesio);        				
			statusView.bringToFront();
		}
		// altrament mirem si te nationality
		else
		{
			// si te nacionality, cal ficar stick corresponent
			if( "nacional.png".equals(nacionality) )
			{
				stickView.setVisibility(View.VISIBLE);
				ImageView statusView = (ImageView)stickView;
				statusView.setImageResource(R.drawable.nacional);
				statusView.bringToFront();
			}
			else if( "extra.png".equals(nacionality) )
			{
				stickView.setVisibility(View.VISIBLE);
				ImageView statusView = (ImageView)stickView;
				statusView.setImageResource(R.drawable.extra);        				
				statusView.bringToFront();
			}
			else
			{
				stickView.setVisibility(View.INVISIBLE);
			}
		}
		
		return playerView;
	}
	
	// this define your drag listener
/*	class MyDragListener implements OnDragListener 
	{
		Drawable dropGreen = getResources().getDrawable(R.drawable.drop_green);
		Drawable dropRed = getResources().getDrawable(R.drawable.drop_red);

		public boolean onDrag(View v, DragEvent event) 
		{
			switch (event.getAction()) 
			{
				case DragEvent.ACTION_DRAG_STARTED:
					// Do nothing
					break;
					
				case DragEvent.ACTION_DRAG_ENTERED:
					//v.setBackgroundDrawable(enterShape);
					v.setBackground(dropGreen);
					break;
					
				case DragEvent.ACTION_DRAG_EXITED:        
					//v.setBackgroundDrawable(normalShape);
					v.setBackground(null);
					break;
					
				case DragEvent.ACTION_DROP:
					v.setBackground(null);
					View view = (View) event.getLocalState();
					String codPlayer = (String)view.getTag();
					ImageView dropView = (ImageView)v;
					imageDownloader.download(String.format(URL_PHOTO_PLAYER, codPlayer), (ImageView) dropView, defaultDrawable);
					break;
					
				case DragEvent.ACTION_DRAG_ENDED:
					v.setBackground(null);
					break;
					
				default:
					break;
			}
			
			return true;
		}
	} */
}
